package com.mengdie.shuidi.ui.dialog;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.blankj.utilcode.utils.EmptyUtils;
import com.blankj.utilcode.utils.LogUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.mengdie.shuidi.AppContext;
import com.mengdie.shuidi.OkHeader;
import com.mengdie.shuidi.R;
import com.mengdie.shuidi.event.CityEvent;
import com.mengdie.shuidi.helper.UIHelper;
import com.mengdie.shuidi.manager.MDModel;
import com.mengdie.shuidi.model.ModelCity;
import com.mengdie.shuidi.model.ModelProvince;
import com.mengdie.shuidi.model.base.BaseEntity;
import com.mengdie.shuidi.ui.adapter.ModelCityAdapter;
import com.mengdie.shuidi.ui.adapter.ModelProvinceAdapter;
import com.mengdie.shuidi.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 作者：HQY on 17/8/22 09:52
 * 邮箱：hqy_xz@126.com
 */

public class AddressDialogFragment extends DialogFragment {


    @Bind(R.id.rv_province_list)
    RecyclerView mRvProvinceList;
    @Bind(R.id.rv_city_list)
    RecyclerView mRvCityList;

    private List<ModelProvince> mProvinceList = new ArrayList<>();
    private ModelProvinceAdapter mProivnceAdpater;
    private List<ModelCity> mCityList = new ArrayList<>();
    private ModelCityAdapter mCityAdapter;
    private ModelCity mCity;

    private String type;
    private String num;

    public static AddressDialogFragment newInstance(String type, String num) {
        Bundle args = new Bundle();
        args.putString(UIHelper.TYPE, type);
        args.putString(UIHelper.NUMBER, num);
        AddressDialogFragment fragment = new AddressDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (EmptyUtils.isNotEmpty(getArguments())) {
            type = getArguments().getString(UIHelper.TYPE);
            num = getArguments().getString(UIHelper.NUMBER);
        }
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.Dialog_Tips);
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_select_address, null);
        builder.setView(view);
        builder.setCancelable(false);
        ButterKnife.bind(this, view);
        initView();
        return builder.create();
    }

    private void initView() {
        mProivnceAdpater = new ModelProvinceAdapter(mProvinceList);
        mRvProvinceList.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRvProvinceList.setAdapter(mProivnceAdpater);
        mRvProvinceList.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {

            }

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemClick(adapter, view, position);
                for (int i = 0; i < mProvinceList.size(); i++) {
                    if (position == i) {
                        mProvinceList.get(i).setShow(true);
                    } else {
                        mProvinceList.get(i).setShow(false);
                    }
                }
                mProivnceAdpater.notifyDataSetChanged();
                getCity(mProvinceList.get(position).getRegionId() + "");
            }
        });
        mCityAdapter = new ModelCityAdapter(mCityList);
        mRvCityList.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRvCityList.setAdapter(mCityAdapter);
        mRvCityList.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {

            }

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemClick(adapter, view, position);
                for (int i = 0; i < mCityList.size(); i++) {
                    if (position == i) {
                        mCityList.get(i).setShow(true);
                    } else {
                        mCityList.get(i).setShow(false);
                    }
                }
                mCityAdapter.notifyDataSetChanged();
                mCity = mCityList.get(position);
            }
        });
        getProivnce();
    }

    /**
     * 获取省份
     */
    private void getProivnce() {
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity()))
                .post(AppContext.getInstance().getBaseUrl() + "pond/get_province")
                .tag("region")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        BaseEntity base = AppContext.getBaseEntity(s);

                        if (base.getRet() == 0) {
                            Gson gson = new Gson();
                            Type provinceType = new TypeToken<BaseEntity<List<ModelProvince>>>() {
                            }.getType();
                            BaseEntity<List<ModelProvince>> mProvinceLists = gson.fromJson(s, provinceType);
                            if (EmptyUtils.isNotEmpty(mProvinceLists.getData())) {
                                mProvinceList = mProvinceLists.getData();
                                getCity(mProvinceList.get(0).getRegionId() + "");
                                mProivnceAdpater.setNewData(mProvinceList);
                            } else {
                                dismiss();
                            }

                        } else {
                            ToastUtil.showToast(base.getMsg());
                        }

                    }
                });

    }

    /**
     * 获取城市
     *
     * @param regionId
     */
    private void getCity(String regionId) {
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity()))
                .post(AppContext.getInstance().getBaseUrl() + "pond/get_city")
                .tag("region")
                .params("region_id", regionId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        BaseEntity base = AppContext.getBaseEntity(s);

                        if (base.getRet() == 0) {
                            Gson gson = new Gson();
                            Type cityType = new TypeToken<BaseEntity<List<ModelCity>>>() {
                            }.getType();
                            BaseEntity<List<ModelCity>> mcityLists = gson.fromJson(s, cityType);
                            if (EmptyUtils.isNotEmpty(mcityLists.getData())) {
                                mCityList = mcityLists.getData();
                                mCityAdapter.setNewData(mCityList);
                            } else {
                                mCityList.clear();
                                mCityAdapter.notifyDataSetChanged();
                            }
                        } else {
                            ToastUtil.showToast(base.getMsg());
                        }
                    }
                });
    }

    @Override
    public void onStart() {
        super.onStart();
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.gravity = Gravity.BOTTOM;
        wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(wlp);
    }


    @OnClick({R.id.tv_address_cacnel, R.id.tv_address_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_address_cacnel:
                dismiss();
                break;
            case R.id.tv_address_submit:
                if (EmptyUtils.isNotEmpty(mCity)) {
                    mDetection(mCity);
                } else {
                    ToastUtil.showToast("请选择城市");
                }
                break;
        }
    }

    private void mDetection(ModelCity city) {
        String cityStr;
        if (num.equals("1")) {
            cityStr = MDModel.getInstance().getCityList();
        } else {
            cityStr = MDModel.getInstance().getShieldCity();
        }
        LogUtils.e("已选城市：" + cityStr);
        if (EmptyUtils.isNotEmpty(cityStr)) {

            Gson gson = new Gson();
            Type cityType = new TypeToken<List<ModelCity>>() {
            }.getType();
            List<ModelCity> cityList = gson.fromJson(cityStr, cityType);
            boolean isHave = false;
            LogUtils.e("已选城市数量：" + cityList.size());
            if (cityList.size() > 0) {
                for (int i = 0; i < cityList.size(); i++) {
                    if (city.getCityId() == cityList.get(i).getCityId()) {
                        isHave = true;
                        break;
                    } else {
                        isHave = false;
                    }
                }
                if (isHave) {
                    ToastUtil.showToast("城市已选！");
                } else {
                    EventBus.getDefault().post(new CityEvent(mCity, type, num));
                    dismiss();
                }
            } else {
                EventBus.getDefault().post(new CityEvent(mCity, type, num));
                dismiss();

            }
        } else {
            EventBus.getDefault().post(new CityEvent(mCity, type, num));
            dismiss();
        }

    }
}
